//聊天的内容展示

import 'dart:convert';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';

import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_keep_alive.dart';
import 'package:hxdj/common/components/my_picture_preview.dart';
import 'package:hxdj/common/components/my_reg_exp_specia_textspan_builder.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/my_get_it.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/message/rongcloud/chat/rc_chat_global_viewmodel.dart';
import 'package:hxdj/message/rongcloud/rc_chat/model/rc_chat_model.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:extended_text/extended_text.dart';

class ChatMessageBaseWidget extends StatefulWidget {
  final ChatMessageBaseModel messageModel;
  const ChatMessageBaseWidget({super.key, required this.messageModel});

  @override
  State<ChatMessageBaseWidget> createState() => _ChatMessageBaseWidgetState();
}

class _ChatMessageBaseWidgetState extends State<ChatMessageBaseWidget> {
  late Widget contentChild;

  @override
  Widget build(BuildContext context) {
    //time
    Widget buildTime() {
      return widget.messageModel.isShowTime
          ? Container(
              padding: EdgeInsets.only(top: 10.h, bottom: 17),
              child: MyText(widget.messageModel.createTime ?? "", color: MyColours.color888888, fontSize: 12.sp),
            )
          : Container();
    }

    //头像
    Widget buildHeader() {
      final RCChatGlobalModel globalModel = serviceLocator<RCChatGlobalModel>();

      // 获取自己的头像
      // RCIMIWUserInfo? imUserInfo = widget.messageModel.userInfo;
      String imageUrl = "";

      // 如果是自己的消息
      if (widget.messageModel.direction == RCIMIWMessageDirection.send) {
        imageUrl = CommonPlugin.sharedPreferences!.getString(MyConstant.userAvatar) ?? "";
      } else {
        imageUrl = globalModel.imUserInfo['headImageName'] ?? "";
      }

      return MyClipRect(
        imageUrl: imageUrl,
        width: 40.w,
        height: 40.w,
        radius: 8.w,
      );
    }

    // 昵称
    Widget buildName() {
      // 获取自己的信息
      // RCIMIWUserInfo? imUserInfo = widget.messageModel.userInfo;
      final RCChatGlobalModel globalModel = serviceLocator<RCChatGlobalModel>();

      String imName = "";

      // 如果是自己的消息
      if (widget.messageModel.direction == RCIMIWMessageDirection.send) {
        imName = CommonPlugin.sharedPreferences!.getString(MyConstant.userNmae) ?? "";
      } else {
        imName = globalModel.imUserInfo["name"] ?? "";
      }

      return !CommonPlugin.isEmpty(imName)
          ? Container(
              padding: EdgeInsets.only(left: 10.w, bottom: 8.h, top: 0),
              child: MyText(imName, color: MyColours.color888888, fontSize: 12.sp),
            )
          : Container();
    }

    switch (widget.messageModel.messageType) {
      case RCIMIWMessageType.text:
        contentChild = ChatMessageTextWidget(messageModel: widget.messageModel);
      case RCIMIWMessageType.image:
        contentChild = ChatMessageImageWidget(messageModel: widget.messageModel);
      default:
        contentChild = ChatMessageUnknownWidget(messageModel: widget.messageModel);
    }

    return MyKeepAliveWrapper(
      key: Key(widget.messageModel.messageUId ?? ""),
      // keepAlive: messageItem?.elemType == MessageElemType.V2TIM_ELEM_TYPE_SOUND,
      child: Container(
          margin: EdgeInsets.only(bottom: 15.h),
          child: Column(children: [
            //时间
            buildTime(),
            //如果是发送方
            widget.messageModel.direction == RCIMIWMessageDirection.send
                ? Container(
                    margin: EdgeInsets.only(left: 47.w, right: 10.w),
                    child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Expanded(
                              child: Container(
                                  padding: EdgeInsets.only(right: 10.w),
                                  child: Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
                                    //昵称
                                    buildName(),
                                    contentChild,
                                  ]))),
                          buildHeader(),
                        ]),
                  )
                : Container(
                    margin: EdgeInsets.only(left: 10.w, right: 47.w),
                    child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          buildHeader(),
                          Expanded(
                            child: Container(
                                padding: const EdgeInsets.only(left: 10),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    buildName(),
                                    contentChild,
                                  ],
                                )),
                          ),
                        ])),
          ])),
    );
  }
}

//聊天内容-文本
class ChatMessageTextWidget extends StatelessWidget {
  final ChatMessageBaseModel messageModel;

  const ChatMessageTextWidget({super.key, required this.messageModel});

  @override
  Widget build(BuildContext context) {
    return MyBorder(
        radius: 12,
        color: MyColours.materialBg,
        child: Container(
            padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 12.w, bottom: 12.w),
            child: ExtendedText(
              (messageModel as ChatMessageTextModel).text ?? "",
              onSpecialTextTap: (dynamic parameter) {
                debugPrint("onSpecialTextTap: $parameter");
                if (parameter.toString().startsWith('\$')) {
                  // launchUrl(Uri.parse('https://github.com/fluttercandies'));
                }
              },
              style: TextStyle(color: MyColours.textBlack, fontSize: 16.sp),
              specialTextSpanBuilder: MyRegExpSpecialTextSpanBuilder(),
              overflow: TextOverflow.ellipsis,
              maxLines: 20,
              //style: TextStyle(background: Paint()..color = Colors.red),
            )));
  }
}

//聊天内容-图片
class ChatMessageImageWidget extends StatelessWidget {
  final ChatMessageBaseModel messageModel;

  const ChatMessageImageWidget({super.key, required this.messageModel});

  @override
  Widget build(BuildContext context) {
    //屏幕的宽度
    double screenWidth = MediaQuery.of(context).size.width;

    //消息
    ChatMessageImageModel imageModel = messageModel as ChatMessageImageModel;

    String heroTag = imageModel.thumbnailBase64String!.substring(0, 100) +
        imageModel.sentTime.toString() +
        imageModel.messageId.toString() +
        imageModel.remote.toString();

    return MyTapWidget(
      onTap: () {
        // 预览图片
        NavigatorUtils.pushParams(context, MyPicturePreviewPage.routeName,
            params: {
              "index": 0,
              "imageBase64s": [imageModel.thumbnailBase64String ?? ""],
              "heroTag": heroTag,
            },
            transition: TransitionType.native);
      },
      child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
        return ConstrainedBox(
            constraints: BoxConstraints(
              maxWidth: screenWidth * 0.5,
              minWidth: 64,
              maxHeight: 256,
            ),
            child: ClipRRect(
              //圆角图片
              borderRadius: BorderRadius.circular(12.w),
              child: Hero(
                tag: heroTag,
                child: Image.memory(base64Decode(imageModel.thumbnailBase64String ?? ""),
                    //防止重绘
                    gaplessPlayback: true,
                    fit: BoxFit.contain),
              ),
            ));
      }),
    );
  }
}

//聊天内容-未识别

class ChatMessageUnknownWidget extends StatelessWidget {
  final ChatMessageBaseModel messageModel;

  const ChatMessageUnknownWidget({super.key, required this.messageModel});

  @override
  Widget build(BuildContext context) {
    return MyBorder(
        radius: 12,
        child: Container(
            padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 12.w, bottom: 12.w),
            child: const MyText(MyConstant.notSupport)));
  }
}
